﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Text.RegularExpressions;
using NPOI.XWPF.UserModel;
using System.IO;
using System.Diagnostics;

namespace FillWordExcelTemplate
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// 存放word中需要替换的关键字以及对应要更改的内容
        /// </summary>
        public Dictionary<string, string> DicWord = new Dictionary<string, string>();
        private string targetPath = "";//生成的临时文件
        public Form1()
        {
            InitializeComponent();
           Helper. BindComboFromTxt(comboBox1);
            comboBox1.SelectedIndex = 0;//默认值0
            axFramerControl1.Titlebar = false;//标题栏隐藏显示
            axFramerControl1.Toolbars = true;//显示隐藏工具栏
            axFramerControl1.Menubar = false;//不显示菜单栏
            axFramerControl1.Visible = false;//不显示
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ReplaceKeyword();
        }
        /// <summary>
        /// 替换关键字
        /// </summary>
        private void ReplaceKeyword()
        {
            try
            {
                string filename = "";//替换后的文件名称
                string TemplateFile = comboBox1.SelectedValue.ToString().Trim();//取下拉列表选中值
                if (TemplateFile == "" || comboBox1.SelectedValue == null)
                {
                    MessageBox.Show("请选择拉列表！");
                }
                else
                {
                    string guid_filename = System.Guid.NewGuid().ToString(); //生成随机文件名                 
                    string FileName = AppDomain.CurrentDomain.BaseDirectory + "Template_Files\\" + TemplateFile;//模板路径
                    string aLastName = FileName.Substring(FileName.LastIndexOf(".") + 1, (FileName.Length - FileName.LastIndexOf(".") - 1)); //扩展名
                    if (aLastName.ToLower() == "docx")
                    {
                        btn_openfile.Text = "用Word打开";
                        axFramerControl1.Close();                  
                        using (FileStream stream = File.OpenRead(FileName))
                        {
                            FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                            XWPFDocument doc = new XWPFDocument(fs);
                           Helper.BindDictWord(DicWord, false);
                            #region NPOI替换
                            //遍历段落                  
                            foreach (var para in doc.Paragraphs)
                            {
                                string oldText = para.ParagraphText;
                                if (oldText != "" && oldText != string.Empty && oldText != null)
                                {
                                    string tempText = para.ParagraphText;
                                    foreach (KeyValuePair<string, string> kvp in DicWord)
                                    {
                                        if (tempText.Contains(kvp.Key))
                                        {
                                            string oldParaText = tempText;
                                            tempText = tempText.Replace(kvp.Key, kvp.Value);                                           
                                            para.ReplaceText(oldParaText, tempText);
                                        }
                                    }
                                }
                            }
                            //遍历表格      
                            var tables = doc.Tables;
                            foreach (var table in tables)
                            {
                                foreach (var row in table.Rows)
                                {
                                    foreach (var cell in row.GetTableCells())
                                    {
                                        foreach (var para in cell.Paragraphs)
                                        {
                                            string oldText = para.ParagraphText;
                                            if (oldText != "" && oldText != string.Empty && oldText != null)
                                            {
                                                //记录段落文本
                                                string tempText = para.ParagraphText;
                                                foreach (KeyValuePair<string, string> kvp in DicWord)
                                                {
                                                    if (tempText.Contains(kvp.Key))
                                                    {
                                                        string oldParaText = tempText;
                                                        tempText = tempText.Replace(kvp.Key, kvp.Value);

                                                        //替换内容
                                                        para.ReplaceText(oldParaText, tempText);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                            #endregion
                            //生成指定文件
                            filename = AppDomain.CurrentDomain.BaseDirectory + "caches\\" + guid_filename + ".docx";
                            targetPath = filename;
                            FileStream output = new FileStream(filename, FileMode.Create);
                            //将文档信息写入文件
                            doc.Write(output);//npoi模式

                            //一些列关闭释放操作
                            fs.Close();
                            fs.Dispose();
                            output.Close();
                            output.Dispose();
                            axFramerControl1.Visible = true;
                            axFramerControl1.Open(filename, true, "Word.Document", "", "");
                        }
                    }
                    else if (aLastName.ToLower() == "xlsx")
                    {
                        btn_openfile.Text = "用Excel打开";                       
                        axFramerControl1.Close();
                        FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read);
                        XSSFWorkbook workbook = new XSSFWorkbook(fs);
                        ISheet sheet = workbook.GetSheetAt(0);
                        IRow row = null;
                        NPOI.SS.UserModel.ICell cell = null;
                       Helper.BindDictWord(DicWord, true);
                            foreach (KeyValuePair<string, string> kvp in DicWord)
                            {
                            string oldlabel = kvp.Key;
                            string newvalue = kvp.Value;
                            for (int i = sheet.FirstRowNum; i <= sheet.LastRowNum; i++)
                            {
                                row = sheet.GetRow(i);
                                for (int k = row.FirstCellNum; k < row.LastCellNum; k++)
                                {
                                    if (row.GetCell(k) != null)
                                    {
                                        cell = row.GetCell(k);
                                       

                                        if (Helper.getCellStringValueAllCase(cell).ToLower() == oldlabel.ToLower())
                                        {
                                            if (Regex.IsMatch(newvalue, @"^[-]?\d+[.]?\d*$") == true)//是否为数字
                                            {
                                                cell.SetCellValue(Convert.ToDouble(newvalue));
                                            }
                                            else
                                            {
                                                if (newvalue == "")
                                                { newvalue = "0"; }
                                                cell.SetCellValue(newvalue);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //生成指定文件
                        filename = AppDomain.CurrentDomain.BaseDirectory + "caches\\" + guid_filename + ".xlsx";
                        targetPath = filename;
                        FileStream output = new FileStream(filename, FileMode.Create);
                        //将文档信息写入文件
                        workbook.Write(output);
                        //一些列关闭释放操作
                        fs.Close();
                        fs.Dispose();
                        output.Close();
                        output.Dispose();
                        axFramerControl1.Visible = true;
                        axFramerControl1.Open(filename, true, "Excel.Sheet", "", "");                      
                    }
                    else
                    {
                        MessageBox.Show("只支持DOCX和XLSX模板文件！");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
     
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                axFramerControl1.Dispose();
                DeleteFolder(AppDomain.CurrentDomain.BaseDirectory + "caches\\");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        /// <summary>
        /// 清空指定的文件夹，但不删除文件夹
        /// </summary>
        /// <param name="dir"></param>
        public static void DeleteFolder(string dir)
        {
            try
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (File.Exists(d))
                    {
                        FileInfo fi = new FileInfo(d);
                        if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                            fi.Attributes = FileAttributes.Normal;
                        File.Delete(d);//直接删除其中的文件  
                    }
                    else
                    {
                        DirectoryInfo d1 = new DirectoryInfo(d);
                        if (d1.GetFiles().Length != 0)
                        {
                            DeleteFolder(d1.FullName);////递归删除子文件夹
                        }
                        Directory.Delete(d);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        /// <summary>
        /// 删除文件夹及其内容
        /// </summary>
        /// <param name="dir"></param>
        public static void DeleteFolder1(string dir)
        {
            try
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (File.Exists(d))
                    {
                        FileInfo fi = new FileInfo(d);
                        if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                            fi.Attributes = FileAttributes.Normal;
                        File.Delete(d);//直接删除其中的文件  
                    }
                    else
                        DeleteFolder(d);////递归删除子文件夹
                    Directory.Delete(d);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }

        }

        private void btn_openfile_Click(object sender, EventArgs e)
        {
            if (btn_openfile.Text == "用Word打开")
            {
                OpenFileWithWord(targetPath);
            }
            else if (btn_openfile.Text == "用Excel打开")
            {
                OpenFileWithExcel(targetPath);
            }
        }
        private void OpenFileWithWord(string targetPath)
        {
            try
            {
                if (targetPath == null || targetPath == "")
                {
                    MessageBox.Show("请先查询后导出报表!");
                }
                else
                {
                    if (Directory.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office17"))
                    {
                        if (File.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office17\WINWORD.exe") == false)
                        {
                            MessageBox.Show("未安装Word 2019");
                        }
                        else
                        {
                            string word = @"C:\Program Files (x86)\Microsoft Office\root\Office17\WINWORD.exe";

                            Process myprocess = new Process();
                            ProcessStartInfo startInfo = new ProcessStartInfo(word, targetPath);
                            myprocess.StartInfo = startInfo;
                            myprocess.StartInfo.UseShellExecute = false;
                            myprocess.Start();
                        }
                    }
                    else if (Directory.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office16"))
                    {
                        if (File.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.exe") == false)
                        {
                            MessageBox.Show("未安装Word 2016");
                        }
                        else
                        {
                            string word = @"C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.exe";

                            Process myprocess = new Process();
                            ProcessStartInfo startInfo = new ProcessStartInfo(word, targetPath);
                            myprocess.StartInfo = startInfo;
                            myprocess.StartInfo.UseShellExecute = false;
                            myprocess.Start();
                        }
                    }

                    else if (Directory.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office15"))
                    {
                        if (File.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office15\WINWORD.exe") == false)
                        {
                            MessageBox.Show("未安装Word 2013");
                        }
                        else
                        {
                            string word = @"C:\Program Files (x86)\Microsoft Office\root\Office15\WINWORD.exe";

                            Process myprocess = new Process();
                            ProcessStartInfo startInfo = new ProcessStartInfo(word, targetPath);
                            myprocess.StartInfo = startInfo;
                            myprocess.StartInfo.UseShellExecute = false;
                            myprocess.Start();
                        }
                    }
                    else if (Directory.Exists(@"C:\Program Files (x86)\Microsoft Office\Office14"))
                    {
                        if (File.Exists(@"C:\Program Files (x86)\Microsoft Office\Office14\WINWORD.exe") == false)
                        {
                            MessageBox.Show("未安装Word 2010");
                        }
                        else
                        {
                            string word = @"C:\Program Files (x86)\Microsoft Office\Office14\WINWORD.exe";

                            Process myprocess = new Process();
                            ProcessStartInfo startInfo = new ProcessStartInfo(word, targetPath);
                            myprocess.StartInfo = startInfo;
                            myprocess.StartInfo.UseShellExecute = false;
                            myprocess.Start();
                        }
                    }
                    else
                    {
                        MessageBox.Show("请按默认位置安装  Word !");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void OpenFileWithExcel(string targetPath)
        {
            try
            {
                if (targetPath == null || targetPath == "")
                {
                    MessageBox.Show("请先查询后导出报表!");
                }
                else
                {
                    if (Directory.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office17"))
                    {
                        if (File.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office17\excel.exe") == false)
                        {
                            MessageBox.Show("未安装Excel 2019");
                        }
                        else
                        {
                            string xlview = @"C:\Program Files (x86)\Microsoft Office\root\Office17\excel.exe";

                            Process myprocess = new Process();
                            ProcessStartInfo startInfo = new ProcessStartInfo(xlview, targetPath);
                            myprocess.StartInfo = startInfo;
                            myprocess.StartInfo.UseShellExecute = false;
                            myprocess.Start();
                        }
                    }
                    else if (Directory.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office16"))
                    {
                        if (File.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office16\excel.exe") == false)
                        {
                            MessageBox.Show("未安装Excel 2016");
                        }
                        else
                        {
                            string xlview = @"C:\Program Files (x86)\Microsoft Office\root\Office16\excel.exe";

                            Process myprocess = new Process();
                            ProcessStartInfo startInfo = new ProcessStartInfo(xlview, targetPath);
                            myprocess.StartInfo = startInfo;
                            myprocess.StartInfo.UseShellExecute = false;
                            myprocess.Start();
                        }
                    }

                    else if (Directory.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office15"))
                    {
                        if (File.Exists(@"C:\Program Files (x86)\Microsoft Office\root\Office15\excel.exe") == false)
                        {
                            MessageBox.Show("未安装Excel 2013");
                        }
                        else
                        {
                            string xlview = @"C:\Program Files (x86)\Microsoft Office\root\Office15\excel.exe";

                            Process myprocess = new Process();
                            ProcessStartInfo startInfo = new ProcessStartInfo(xlview, targetPath);
                            myprocess.StartInfo = startInfo;
                            myprocess.StartInfo.UseShellExecute = false;
                            myprocess.Start();
                        }
                    }
                    else if (Directory.Exists(@"C:\Program Files (x86)\Microsoft Office\Office14"))
                    {
                        if (File.Exists(@"C:\Program Files (x86)\Microsoft Office\Office14\excel.exe") == false)
                        {
                            MessageBox.Show("未安装excel2010");
                        }
                        else
                        {
                            string xlview = @"C:\Program Files (x86)\Microsoft Office\Office14\excel.exe";

                            Process myprocess = new Process();
                            ProcessStartInfo startInfo = new ProcessStartInfo(xlview, targetPath);
                            myprocess.StartInfo = startInfo;
                            myprocess.StartInfo.UseShellExecute = false;
                            myprocess.Start();
                        }
                    }
                    else
                    {
                        MessageBox.Show("请按默认位置安装  Excel !");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}
